//
// Created by 吴喆 on 2020/3/7.
//

#import "DemoPlayer.h"
#include "../engine/Gui.h"
#include "DemoMonster.h"

DemoPlayer::DemoPlayer(Scene *scene_) : Player(scene_) {
    init();
}

void DemoPlayer::render() {
    for (auto bullet : bullets) {
        bullet->render();
    }
    Texture2D *currTexture = Playable::currentAnimation->updateAndGetCurrentFrame();
    if (isAtked) {

        renderer->DrawSprite(scene->getCamera(), currTexture, GameObject::currPosition,
                            GameObject::size, 0.0f,
                            Playable::direction == DIRECTION::LEFT, false, true, glm::vec4(1));

        interval += CTime::getInstance()->getDelta();
        if (AtkedStateInterval <= interval) {
            isAtked = false;
            interval = 0;
        }
    } else {
        renderer->DrawSprite(scene->getCamera(), currTexture, GameObject::currPosition,
                            GameObject::size, 0.0f,
                            Playable::direction == DIRECTION::LEFT);
    }

}

void DemoPlayer::initPlayerStateMachine() {
    auto demoPlayerStateMachine = new DemoPlayerStateMachine();
    Playable::machines.push_back(demoPlayerStateMachine);
    auto directionStateMachine = new DirectionStateMachine();
    Playable::machines.push_back(directionStateMachine);
    auto atkStateMachine = new AtkStateMachine();
    Playable::machines.push_back(atkStateMachine);
}

void DemoPlayer::initGameObject() {
    Player::initGameObject();
    GameObject::initPosition = glm::vec2(0, 3);
}

void DemoPlayer::init() {
    Player::init();
}

void DemoPlayer::launchBullet() {
    bullets.emplace_back(new DemoBullet(scene, this, glm::vec2(
            (direction == DIRECTION::LEFT ? currPosition.x - 1 : currPosition.x + 1), GameObject::currPosition.y)));
}

void DemoPlayer::update() {
    Player::update();

    invincibleInterval += CTime::getInstance()->getDelta();

    // bullet update
    for (auto bullet = bullets.begin(); bullet != bullets.end();) {
        if ((*bullet)->isOver) {
            delete (*bullet);
            bullets.erase(bullet++);
        } else {
            (*bullet)->update();
            ++bullet;
        }
    }
    Gui::getInstance()->showPlayerPos1(body.instance->GetPosition().x, body.instance->GetPosition().y);

}

void DemoPlayer::beAtked(GameObject *gameObject) {
    if (invincibleInterval >= AtkedInvincibleInterval) {
        auto p = dynamic_cast<DemoMonster *>(gameObject);
        if (p) {
            isAtked = true;
            interval = 0;
            invincibleInterval = 0;
        }
    }
}
